package com.order.controller.back_end;


import com.order.common.AuthAccess;
import com.order.dao.Desk;
import com.order.dao.Result;
import com.order.service.DeskService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@RestController
@Scope("prototype")
@AllArgsConstructor
public class DeskController {

    private DeskService deskService;

//    查询所有饭桌
    @RequestMapping ("/desk_select")
    public Result select(Desk desk){
        List<Desk> desks;
        try{
            desks = deskService.getDesks(desk);
        } catch (Exception e){
            if(e instanceof DuplicateKeyException){
                return Result.error("查询数据库错误");
            }else {
                return Result.error("系统错误");
            }
        }
        log.info("响应成功");

        return Result.success(desks);
    }

//   新增饭桌
    @RequestMapping("/desk_add")
    public String add(@RequestBody Desk desk,String name) {

        int count = deskService.judgment(name);
          if(count > 0){
              log.info("该饭桌已存在，不可增加！");
              return "新增失败";
          }
          else {
              int result = deskService.addDesk(desk);
              String deskName= desk.getName();
              if(result > 0){
                  log.info("新增"+ deskName+"成功！");
                  return "新增成功";
              }else {
                  log.info("新增失败");
                  return "新增失败";
              }
          }
    }

//    删除饭桌（修改del值为 1 ）
    @RequestMapping("/desk_delete/{id}")
    public String deleteDesk(@PathVariable("id") int id){
        int count = deskService.deleteDesk(id);
        if( count>0 ){
            log.info("删除"+ id +"号成功");
            return "删除成功";
        }else {
            return "删除失败";
        }
    }

//    预定饭桌
    @RequestMapping("/desk_book/{id}/{state}")
    public String changeDesk(@PathVariable("id") int id ,@PathVariable("state") int state, Desk desk){

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int count = deskService.changeStatus(desk);
        if( count>0 ){
            if(state == 1){
                log.info("预定"+ id +"号桌成功");
                desk.setBooktime(df.format(System.currentTimeMillis()));
                deskService.changeStatus(desk);
                return "预定成功";
            }
            else {
                log.info("退订" + id + "号桌成功");
                desk.setBooktime(null);
                return "退桌成功";
            }
        }else {
            if(state == 1){
                log.info("预定"+ id +"号桌失败");
                return "预定失败";
            }
            else {
                log.info("退桌失败");
                return "退桌失败";
            }
        }
    }




}
